﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using AirLinq.Providers.Sql;

namespace AirLinq.Providers {
	public static class DatabaseProviderFactory {
		private static Dictionary<string, Type> _registeredProviders;
		static DatabaseProviderFactory() {
			_registeredProviders = new Dictionary<string,Type>();
			RegisterProvider<SqlDatabaseProvider>(typeof(SqlConnection).FullName);
		}
		public static IDatabaseProvider CreateDatabaseProvider(IDbConnection conection) {
			if (conection == null) {
				throw new ArgumentNullException("connection");
			}
			var dbconection = conection as DbConnection;
			Type dbProvideerType;
			//if (dbconection != null) {
			//	if (conection.State != ConnectionState.Open) {
			//		throw new ArgumentException("Connection must be opened");
			//	}
			//	if (!_registeredProviders.TryGetValue(dbconection.ServerVersion, out dbProvideerType)) {
			//		throw new NotSupportedException(string .Format("database '{0}' not supported", dbconection.ServerVersion));
			//	}
			//} else {
				if (!_registeredProviders.TryGetValue(conection.GetType().FullName, out dbProvideerType)){
					throw new NotSupportedException(string.Format("database '{0}' not supported", conection.GetType().FullName));
				}
			//}
			return (IDatabaseProvider) Activator.CreateInstance(dbProvideerType);
		}
		public static void RegisterProvider<T>(string databaseType) where T:IDatabaseProvider, new() {
			lock (_registeredProviders) {
				_registeredProviders[databaseType] = typeof(T);
			}
		}
	}
}
